package com.ruoyi.web.controller.teaching;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.shiro.util.AuthorizationUtils;
import com.ruoyi.system.domain.CityData;
import com.ruoyi.system.domain.SysCityData;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.teaching.domain.TeachingFile;
import com.ruoyi.teaching.service.ITeachingFileService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.teaching.domain.TeachingSchool;
import com.ruoyi.teaching.service.ITeachingSchoolService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 教务校区Controller
 *
 * @author William
 * @date 2022-10-10
 */
@Controller
@RequestMapping("/teaching/school")
public class TeachingSchoolController extends BaseController {
    private String prefix = "teaching/school";

    @Autowired
    private ITeachingSchoolService teachingSchoolService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private ITeachingFileService teachingFileService;

    @RequiresPermissions("teaching:school:view")
    @GetMapping()
    public String school() {
        return prefix + "/school";
    }

    /**
     * 查询教务校区列表
     */
    @RequiresPermissions("teaching:school:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TeachingSchool teachingSchool) {
        startPage();
        List<TeachingSchool> list = teachingSchoolService.selectTeachingSchoolList(teachingSchool);
        return getDataTable(list);
    }

    /**
     * 导出教务校区列表
     */
    @RequiresPermissions("teaching:school:export")
    @Log(title = "教务校区", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TeachingSchool teachingSchool) {
        List<TeachingSchool> list = teachingSchoolService.selectTeachingSchoolList(teachingSchool);
        ExcelUtil<TeachingSchool> util = new ExcelUtil<TeachingSchool>(TeachingSchool.class);
        return util.exportExcel(list, "教务校区数据");
    }

    /**
     * 新增教务校区
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存教务校区
     */
    @RequiresPermissions("teaching:school:add")
    @Log(title = "教务校区", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional()
    public AjaxResult addSave(TeachingSchool teachingSchool) {

        teachingSchool.setCreateId(getUserId());
        teachingSchool.setCreateBy(getLoginName());
        teachingSchool.setCreateTime(new Date());
        int i = teachingSchoolService.insertTeachingSchool(teachingSchool);
         /*
            新增和修改时判断是否已经创建了部门
        * */
        SysDept dept = new SysDept();
        dept.setParentId(100L);
        dept.setSchoolId(teachingSchool.getSchoolId());
        dept.setDeptName(teachingSchool.getName());
        dept.setCreateBy(getLoginName());
        dept.setCreateTime(DateUtils.getNowDate());
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        deptService.insertDept(dept);
        return toAjax(i);
    }

    /**
     * 修改教务校区
     */
    @RequiresPermissions("teaching:school:edit")
    @GetMapping("/edit/{schoolId}")
    public String edit(@PathVariable("schoolId") Long schoolId, ModelMap mmap) {
        TeachingSchool teachingSchool = teachingSchoolService.selectTeachingSchoolBySchoolId(schoolId);
        mmap.put("teachingSchool", teachingSchool);
        return prefix + "/edit";
    }

    /**
     * 修改保存教务校区
     */
    @RequiresPermissions("teaching:school:edit")
    @Log(title = "教务校区", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional()
    public AjaxResult editSave(TeachingSchool teachingSchool) {
        teachingSchool.setUpdateBy(getLoginName());
        teachingSchool.setUpdateTime(new Date());

        int i = teachingSchoolService.updateTeachingSchool(teachingSchool);
         /*
            新增和修改时判断是否已经创建了部门
        * */
        SysDept dept = new SysDept();
        dept.setParentId(100L);
        dept.setSchoolId(teachingSchool.getSchoolId());
        //如果已经存在 则修改 没有就新增
        List<SysDept> list = deptService.selectDeptList(dept);
        if (list.size() == 0) {
            SysDept param = new SysDept();
            param.setParentId(100L);
            List<SysDept> currentDepts = deptService.selectDeptList(param);
            dept.setOrderNum(currentDepts.size() + 1);
            dept.setDeptName(teachingSchool.getName());
            dept.setLeader(teachingSchool.getPrincipal());
            dept.setPhone(teachingSchool.getPrincipalPhone());
            dept.setCreateBy(getLoginName());
            dept.setCreateTime(DateUtils.getNowDate());
            if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
                return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            }
            deptService.insertDept(dept);
        } else {
            dept = list.get(0);
            dept.setLeader(teachingSchool.getPrincipal());
            dept.setPhone(teachingSchool.getPrincipalPhone());
            if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
                return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            } else if (dept.getParentId().equals(dept.getDeptId())) {
                return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
            } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
                return AjaxResult.error("该部门包含未停用的子部门！");
            }
            dept.setUpdateBy(getLoginName());
            dept.setUpdateTime(DateUtils.getNowDate());
            deptService.updateDept(dept);
        }

        return toAjax(i);
    }

    /**
     * 删除教务校区
     */
    @RequiresPermissions("teaching:school:remove")
    @Log(title = "教务校区", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(teachingSchoolService.deleteTeachingSchoolBySchoolIds(ids));
    }

    /**
     * 校区详情
     */
    @GetMapping("/info/{schoolId}")
    public String Info(@PathVariable("schoolId") Long schoolId, ModelMap mmap) {
        TeachingSchool teachingSchool = teachingSchoolService.selectTeachingSchoolBySchoolId(schoolId);
        mmap.put("teachingSchool", teachingSchool);
        return prefix + "/info";
    }

    /**
     * 三级联动 校区选择
     */
    @GetMapping("/select")
    @ResponseBody
    public List<TeachingSchool> select() {
        List<TeachingSchool> list1 = teachingSchoolService.selectTeachingSchoolList(new TeachingSchool());
        return list1;
    }

    /**
     * 学校账号管理
     */
    @PostMapping("/accountList")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        startPage();
        //系统用户为员工
        user.setUserType("00");
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        return toAjax(userService.changeStatus(user));
    }

    /**
     * 新增用户
     */
    @GetMapping("/addUser")
    public String add(@RequestParam("schoolId") Long schoolId, ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        mmap.put("schoolId", schoolId);
        return prefix + "/addUser";
    }

    @GetMapping("/editUser/{userId}")
    public String editUser(@PathVariable("userId") Long userId, ModelMap mmap) {
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/editUser";
    }

    @PostMapping("/removeUser")
    @ResponseBody
    public AjaxResult removeUser(String ids) {
        if (ArrayUtils.contains(Convert.toLongArray(ids), getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(ids));
    }

    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue()) {
                setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    @PostMapping("/listFile")
    @ResponseBody
    public TableDataInfo list(TeachingFile teachingFile) {
        startPage();
        List<TeachingFile> list = teachingFileService.selectTeachingFileList(teachingFile);
        return getDataTable(list);
    }

    @GetMapping("/uploadFile")
    public String addFle(@RequestParam("schoolId") Long schoolId, ModelMap mmap) {
        mmap.put("schoolId", schoolId);
        return prefix + "/upload";
    }

    @PostMapping("/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(@RequestBody List<TeachingFile> teachingFile) throws IOException {
        for (TeachingFile file : teachingFile) {
            file.setCreateId(getUserId());
            file.setCreateBy(getLoginName());
            file.setCreateTime(new Date());
            teachingFileService.insertTeachingFile(file);
        }
        return success(teachingFile);
    }


    @PostMapping("/addUser")
    @ResponseBody
    public AjaxResult addUserSave(@Validated SysUser user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(getLoginName());
        return toAjax(userService.insertUser(user));
    }

    @PostMapping("/editUser")
    @ResponseBody
    public AjaxResult editUserSave(@Validated SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(userService.updateUser(user));

    }

    @GetMapping("/statisticBySchoolId/{schoolId}")
    @ResponseBody
    public AjaxResult selectSchoolStatisticVoBySchoolId(@PathVariable("schoolId") Long schoolId) {
        return success(teachingSchoolService.selectSchoolStatisticVoBySchoolId(schoolId));
    }

}
